package com.zhiwei.save;

import java.util.List;

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.zhiwei.entity.TiebaData;

public class SaveToMongo {
    
    public static void saveToMongoDB(List<TiebaData> lists,String word,String dataBase,String dbtable){
        MongoCollection<Document> mongoCollection = LinkMongo.getMongoCollection(dataBase,dbtable);
        int i = 1;
        for(TiebaData tiebaData : lists) {
            Document document = new Document();
            document.append("_id", tiebaData.getUrl());
            document.append("url", tiebaData.getUrl());
            document.append("title", tiebaData.getTitle());
            document.append("content", tiebaData.getContent());
            document.append("source", tiebaData.getSource());
            document.append("time", tiebaData.getTime());
            document.append("author", tiebaData.getAuthor());
            document.append("word", word);
            FindIterable<Document> iter = mongoCollection.find(new Document("_id",tiebaData.getUrl()));
            MongoCursor<Document> cursor = iter.iterator();
            if(cursor.hasNext()) {
                mongoCollection.replaceOne(new BasicDBObject("_id", tiebaData.getUrl()), document);
                i++;
            }else {
                mongoCollection.insertOne(document);
            }
            cursor.close();
        }
        System.out.println(i);
        LinkMongo.closeMongoCollection();
    }
    
}
